<template>
  <div class="app-container" v-loading="pageLoading">
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="panel-info">
          <div class="panel-title">标签模板列表</div>
          <div class="panel-body">
            <div class="filter-container">
              <el-select style="width: 220px" v-model="query.type" class="filter-item" placeholder="请选择标签类型" clearable>
                <el-option v-for="i in typeOptions" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
              <el-select style="width: 220px" v-model="query.level" class="filter-item" placeholder="请选择标签层级" clearable>
                <el-option v-for="i in levelOptions" :key="i.value" :label="i.label" :value="i.value">
                </el-option>
              </el-select>
              <el-input style="width: 220px" placeholder="输入标签名称查询" clearable prefix-icon="el-icon-search"
                class="filter-item" @keyup.enter.native="research" @clear="research" v-model="query.queryString">
              </el-input>
            </div>
            <div class="filter-container">
              <el-select style="width: 200px" v-model="query.materialId" class="filter-item" filterable remote
                reserve-keyword placeholder="请选择物料" :remote-method="querySearchAsync" clearable>
                <el-option v-for="item in restaurants" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <el-button class="filter-item " type="success" plain @click="research">查询</el-button>
              <el-button class="filter-item " type="info" plain @click="exportData"
                v-permission="'labelDesign.exportData'" :loading="exportLoading">导出</el-button>
              <el-button type="primary" class="filter-item " @click="createItems" v-permission="'labelDesign.add'">
                创建标签模板
              </el-button>
            </div>
            <z-table :list="list" :tableProps="tableProps" @row-click="mainRowClick" :columns="columns"
              @editItem="editItems" @deleteItem="deleteItem">
            </z-table>
            <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
              @change="getList"></z-pagination>
          </div>
        </div>
      </el-col>
      <el-col :span="12" v-show="row.id">
        <div class="panel-info">
          <div class="panel-title">标签模板打印设定</div>
          <div class="panel-body">
            <ma-label :row="row" />
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="data.id ? '编辑' : '创建'" :width="formProps.dialogWidth" :close-on-click-modal="false"
      :visible.sync="editFormVisible">
      <div style="padding-right: 100px">
        <el-form :model="data" v-bind="formProps">
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否通用">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>是否通用</span>
                </span>
                <el-select v-model="data.is_common" clearable filterable style="width: 100%" @change="commonChange"
                  :disabled="!!data.id">
                  <el-option label="否" :value="0"> </el-option>
                  <el-option label="是" :value="1"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="档案类型">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>档案类型</span>
                </span>
                <el-select v-model="data.document_type" clearable filterable style="width: 100%" @change="typeChange"
                  :disabled="!!data.id">
                  <el-option v-for="o in typeOptions" :key="o.value" :label="o.label" :value="o.value"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="data.is_common==0">
              <el-form-item label="标签类型">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>标签类型</span>
                </span>
                <el-select v-model="data.label_type" clearable filterable style="width: 100%" @change="labelTypeChange">
                  <el-option v-for="o in labelTypeOptions" :key="o.value" :label="o.label" :value="o.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="data.label_type==3 && data.is_common==0">
              <el-form-item label="标签层级">
                <el-select v-model="data.level" clearable filterable style="width: 100%">
                  <el-option v-for="o in levelOptions" :key="o.value" :label="o.label" :value="o.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="(data.document_type == 2 || data.document_type == 3)">
            <el-col :span="24">
              <el-form-item label="上传标签档案">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>上传标签档案</span>
                </span>
                <el-upload :file-list="data.labels" v-bind="labelUploaderProps">
                  <el-button size="mini" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="data.document_type == 1">
            <el-col :span="12">
              <el-form-item label="标签名称">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>标签名称</span>
                </span>
                <el-input v-model="data.name" clearable style="width: 100%"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="!!data.id">
              <el-form-item label="标签尺寸">
                <el-input class="mr-10" v-if="data.size" v-model="data.size" clearable style="width: 160px" disabled>
                </el-input>
                <el-button type="success" @click="labelDesign(data.id)">标签设计</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="data.remarks" type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="text-right">
          <el-button @click="editFormVisible = false">取消</el-button>
          <el-button v-if="!formProps.disabled" type="primary" @click.native="submit" :loading="submitLoading">
            {{ data.type == 1 && !data.id ? '保存并开始设计' : '确认' }}
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" class="design-dialog" title="标签设计"
      :visible.sync="designVisible" width="80%">
      <iframe :src="designUrl" width="100%" scrolling='auto' style="min-height: 550px"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import commonMixin from '@/views/_common/mixin'
import maLabel from '@/views/masterdata/barcode/maLabel'
export default {
  mixins: [commonMixin],
  components: { maLabel },
  name: 'labelDesign',
  data: function () {
    return {
      api: this.$api.label,
      apiSingle: this.$api.label + 'getbyid',
      baseUrl: this.$api.baseUrl,
      apiCreate: this.$api.label + 'modify',
      apiEdit: this.$api.label + 'modify',
      name: '物料标签档案',
      columns: [
        { title: '是否通用', key: 'is_common_name', width: 80 },
        { title: '档案类型', key: 'document_type_name', width: 120 },
        { title: '标签类型', key: 'label_type_name', width: 120 },
        { title: '标签层级', key: 'level_name', width: 160 },
        { title: '标签名称', key: 'name' },
        { title: '备注', key: 'remarks' },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      fields: [],
      query: {
        cust_id: null,
        key_part_no: null,
      },
      tableProps: {
        border: true,
        opsColWith: 80,
        hideOperations: false,
        highlightCurrentRow: true,
      },
      formProps: {
        dialogWidth: '80%',
        labelWidth: '120px',
      },
      initData: { labels: [], name: '', document_type: '', is_common: 0 },
      typeOptions: [
        { label: '在线设计', value: 1 },
        { label: 'CodeSoft', value: 2 },
        { label: 'Bartender', value: 3 },
      ],
      labelUploaderProps: {},
      designBaseUrl: '/labelDesign/index.html',
      designUrl: '',
      designVisible: false,
      row: {},
      dicObj: {},
      labelTypeOptions: [],
      levelObj: {},
      levelOptions: [],
      // 上传
      formData: null,
      restaurants: [],
    }
  },
  mounted() {
    window.addEventListener(
      'message',
      (e) => {
        if (window.electron) {
          window.electron.zpl(e.data)
        }
      },
      false,
    )
  },
  methods: {
    research() {
      this.row = {}
      this.getList()
    },
    //物料远程搜索
    querySearchAsync(queryString) {
      let params = {
        queryString: queryString,
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'masterdata/mat/getlist_v10', params).then((res) => {
        this.restaurants = res.list.map((i) => {
          return {
            label: i.key_part_no + '/' + i.key_part_name,
            value: i.id,
          }
        })
      })
    },

    // 创建标签模板
    createItems() {
      this.formData = new FormData()
      this.createItem()
    },
    // 编辑标签模板
    editItems(v) {
      this.formData = new FormData()
      this.editItem(v)
    },
    commonChange() {
      if (this.data.is_common == 1) {
        this.data.document_type = ''
        this.data.level = ''
      }
    },
    labelTypeChange() {
      if (this.data.label_type != 3) this.data.level == null
    },
    mainRowClick(row) {
      this.row = row
    },
    typeChange(v) {
      if (v == 2) {
        this.data.size = ''
        this.data.content = '{}'
        this.labelUploaderProps = {
          limit: 1,
          action: '',

          'auto-upload': false,
          onSuccess: this.afterUpload,
          onRemove: this.onRemove,
          onPreview: this.onPreview,
          onExceed: this.onExceed,
          onChange: this.onChange,
          headers: { Authorization: 'Bearer ' + getToken() },
        }
      } else if (v == 3) {
        this.data.size = ''
        this.data.content = '{}'
        this.labelUploaderProps = {
          limit: 1,
          action: '',
          accept: '.btw',
          'auto-upload': false,
          onSuccess: this.afterUpload,
          onRemove: this.onRemove,
          onPreview: this.onPreview,
          onExceed: this.onExceed,
          onChange: this.onChange,
          headers: { Authorization: 'Bearer ' + getToken() },
        }
      } else {
        this.formData = new FormData()
      }
    },
    labelDesign(id) {
      if (this.editFormVisible) this.editFormVisible = false
      let updateUrl = encodeURIComponent(this.apiEdit)
      let getSingleUrl = encodeURIComponent(this.apiSingle)
      // this.designUrl = `${this.designBaseUrl}?id=${id}&get=${getSingleUrl}&update=${
      //   this.$api.label + 'updateContent'
      // }&token=${getToken()}&t=${Date.now()}&toZpl=${this.$api.label + 'bitmaptozpl'}`
      // this.designVisible = true
      this.designUrl = `${this.designBaseUrl}?id=${id}&api=${this.$api.label}`
      this.designVisible = true
    },
    handleDesignClose() {
      return true
    },
    designSubmit() {},
    formatList(list) {
      //依据实际需求处理
      list.forEach((i) => {
        let typename = this.typeOptions.find((j) => j.value == i.document_type)
        i.level_name = this.levelObj[i.level]
        i.document_type_name = typename ? typename.label : ''
        i.label_type_name = this.dicObj[i.label_type]
        i.is_common_name = i.is_common == 0 ? '否' : '是'
      })
      return list
    },
    formatAfterGet(data) {
      //依据实际需求处理
      data.labels = data.file_list.length ? [{ name: data.file_list[0].name, url: data.file_list[0].url }] : []
      data.label_type = data.label_type.toString()
      return data
    },
    submit() {
      this.submitLoading = true
      let url = this.apiEdit
      if (!this.data.document_type) {
        this.submitLoading = false
        return this.$message.error('档案类型必填')
      }
      if (this.data.is_common == 0 && !this.data.label_type) {
        this.submitLoading = false
        return this.$message.error('标签类型必填')
      }
      if ((this.data.document_type == 2 || this.data.document_type == 3) && !this.data.name) {
        this.submitLoading = false
        return this.$message.error('需要上传标签档案')
      }
      if (this.data.document_type == 1 && !this.data.name) {
        this.submitLoading = false
        return this.$message.error('标签名称为必填项')
      }
      this.formData.append('model', JSON.stringify(this.data))
      this.$request(url, this.formData, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.editFormVisible = false
          this.getList()

          if (!this.data.id && this.data.type == 1 && r) {
            labelDesign(r)
          }
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    formatBeforeSave(data) {
      //依据实际需求处理
      let tmp = _.cloneDeep(data)
      // if (tmp.file_path && tmp.file_path.data && tmp.file_path.data.length) {
      //   tmp.file_path = tmp.file_path.data[0].file_path
      // }
      return tmp
    },
    afterUpload(r, f, l) {
      // this.$message({
      //   message: '上传成功',
      //   type: 'success',
      // })
      // this.data.name = f.name
      // this.data.file_path = r
    },
    onRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`, '请确认', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.formData = new FormData()
        fileList.forEach((i) => {
          if (!i.FileId && i.name != file.name) {
            this.formData.append('files', i.raw)
          }
        })
      })
    },
    onPreview(f) {
      if (f.url) this.newLink(f.url)
    },
    onExceed(files, fileList) {
      this.$message({
        message: '只允许上传一个文件，如许更改，请先删除已上传的文件。',
        type: 'error',
      })
    },
    // 上传
    onChange(file) {
      this.data.name = file.name
      this.formData.append('files', file.raw)
    },
    newLink(url) {
      let a = document.createElement('a')
      a.setAttribute('href', url)
      a.setAttribute('target', '_blank')
      a.click()
      a.remove()
    },
  },
  created: function () {
    this.$request(this.$api.dictionary + 'getdirectchildren', {
      parentType: 'package_level_name',
    }).then((r) => {
      r.forEach((v) => {
        this.levelObj[v.value] = v.label
      })

      this.levelOptions = r
    })

    this.$request(this.$api.dictionary + 'getdirectchildren', {
      parentType: 'barcode_label_type',
    }).then((r) => {
      this.labelTypeOptions = r
      r.forEach((v) => {
        this.dicObj[v.value] = v.label
      })
    })

    this.getList()

    this.labelUploaderProps = {
      limit: 1,
      action: '',
      'auto-upload': false,
      onSuccess: this.afterUpload,
      onRemove: this.onRemove,
      onPreview: this.onPreview,
      onExceed: this.onExceed,
      onChange: this.onChange,
      headers: { Authorization: 'Bearer ' + getToken() },
    }
  },
}
</script>
<style lang="scss" scoped>
::v-deep .design-dialog .el-dialog__body {
  padding: 0 !important;
}
</style>
